<?php
// +----------------------------------------------------------------------
// | ZanPianCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.zanpiancms.com All rights reserved.
// +----------------------------------------------------------------------
// | BBS:  <http://www.zanpiancms.cc>
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use think\Cache;
use app\common\library\Letter;
class Tv extends Model{
    // 定义时间戳字段名
    protected $createTime = '';
    protected $updateTime = '';
	// 自动完成
	protected $auto = [];
	protected $insert = ['tv_addtime','tv_lasttime'];
	protected $update = [];
    protected $type = [
        'tv_data'    =>  'json',
    ];
	public $weeklist = array(1=>'星期一',2=>'星期二',3=>'星期三',4=>'星期四',5=>'星期五',6=>'星期六',7=>'星期日');
    public $weeklists = array(0=>'星期日',1=>'星期一',2=>'星期二',3=>'星期三',4=>'星期四',5=>'星期五',6=>'星期六');		
	//自动完成相关字段
	protected function setTvAddtimeAttr($value,$data){
		if (!empty($data['tv_checktime']) || empty($value)) {
			return time();
		}else{
			return strtotime($value);
		}
	}
	protected function setTvLasttimeAttr($value){
		return time();
	}	
	protected function setTvkeywordsAttr($value,$data){
		if(!empty($value)){
			return $value;
		}elseif(empty($value) && !empty($data['tv_name']) && !empty($data['auto_keywords'])){
			$get=controller('get');
			$info=$get->keywords($data['tv_name'],1);
			if($info['code']=1){
			    return $info['data']['str'];	
			}else{
				return '';
			}
		}else{
			return '';
		}
	}
	protected function setTvTagAttr($value,$data){
		if(empty($value) && !empty($data['auto_tag'])){
			return zanpian_get_tag($data['tv_name'],$data['tv_content']);
		}else{
			return $value;
		}
	}
    protected function setTvPrtyAttr($value){
        if(!is_array($value)){
            return 0;
        }else{
            $attribute = 0;
            foreach ($value as $key=>$value){
                $attribute += $value;
            }
            return $attribute;
        }
    }	
	protected function setTvLetterAttr($value,$data){
		$Letter = new Letter();
		if ($data['tv_name']) {
			return $Letter->getletter($data['tv_name']);
		}
	}
    protected function setTvLettersAttr($value,$data){
	    $Letter = new Letter();
	    if(empty($value)) {
		    return $Letter->getletters(trim($data['tv_name']),7);
		}else{
		    return trim($value);
		}
    }
	protected function setTvPicAttr($value){
		$img = model('Img');
		$file=$img->down_load(trim($value),'tv');
		return $file['file'];
	}
	protected function setTvContentAttr($value){	
	    if(!empty($value)){
	       return zanpian_content_down_images(trim($value),'tv');
	    }else{
	       return ''; 	 
	    }
	}
	protected function setTvGoldAttr($value){
		if($value > 10){
			$value = 10;
		}	
		return 	$value;
	}
	protected function setTvDataAttr($value,$data){
		if (!empty($data['tv_checkdata']) && !empty($data['tv_apiid']) && !empty($data['tv_apitype'])){
			$get=controller('get');
			$info=$get->jiemu($data['tv_apiid'],$data['tv_apitype'],1);
			if(!empty($info) && $info['code']==1){
			    return json_encode($info['data']);
			}else{
				if(!empty($value)){
				    return json_encode($value);
				}
			}
		}else{
			return json_encode($value);
		}
	}	
	//事件注册
    protected static function init(){
		//写入后置事件
		Tv::afterWrite(function ($tv){
			if(isset($tv->tv_tag)){
			    model('Tag')->tag_updata($tv->tv_id,7,$tv->tv_tag);
			}
			if(!empty($tv->tv_id)){
			   model('Manage')->DelCache(7,$tv->tv_id);
			}		
		});		
		//删除后置事件
        Tv::afterDelete(function ($tv){
			model('Tag')->tag_updata($tv->tv_id,7);
			zanpian_del_img_file($tv->tv_content);
			//删除图片和缩略图
            if(!empty($tv->tv_pic) && file_exists(ROOT_PATH.$tv->tv_pic)){
                @unlink(ROOT_PATH.$tv->tv_pic);			
            }
			model('Manage')->DelCache(7,$tv->tv_id);
       });	
    }
    //数据查询	
    public function listData($tag){
		$param = zanpiancms_param_url();
		if(!is_array($tag)) {
            $tag=json_decode($tag, true);
        }
		$tag['field']= !empty($tag['field']) ? $tag['field'] : '*';
		$tag['limit']= !empty($tag['limit']) ? $tag['limit'] : 10;
		if(!empty($tag['page']) && !empty($param['order'])){
			$tag['order']='tv_'.$param['order'].' desc';
		}		
		if(empty(order_check($tag['order']))){
			$tag['order']='tv_addtime desc';
		}
		$cahce=tag_cache($tag);
	    //优先从缓存调用数据及分页变量
		if(!empty($cahce['cache_name']) && !empty($cahce['cache_time'])){			
			$data_cache_content = Cache::get($cahce['cache_name']);
			if($data_cache_content){
				return $data_cache_content;
			}
		}		
		$where=[];
		$where['tv_status']=['eq',1];
	    if(!empty($tag['ids'])){
		     $where['tv_id'] = array('in',$tag['ids']);
	    }
	    if(!empty($tag['not'])){
		     $where['tv_id'] = array('not in',$tag['not']);
	    }		
	    if (!empty($tag['letter'])) {
		    $letter = explode(',',$tag['letter']);
		    if(count($letter)>1) {
			    $where['tv_letter'] = array('in',$tag['letter']);
		    }else{
			    $where['tv_letter'] = array('eq',$letter[0]);
		    }
	    }		
	    if(!empty($tag['cid'])) {
		    $cids = explode(',',trim($tag['cid']));
		    if(count($cids) > 1) {
			    $where['tv_cid'] = array('in',getlistarr_tag($cids));
		    }else{
			    $where['tv_cid'] = getlistsqlin($tag['cid']);
		    }
	    }		
	    if(!empty($tag['stars'])) {
		     $where['tv_stars'] = array('in',$tag['stars']);
	    }
	    if (!empty($tag['hits'])) {
		    $hits = explode(',',$tag['hits']);
		    if (count($hits) > 1) {
			    $where['tv_hits'] = array('between',$hits[0].','.$hits[1]);
		    }else{
			    $where['tv_hits'] = array('gt',$hits[0]);
		    }
	    }
	    if(!empty($tag['name'])) {
		    $name = explode(',',$tag['name']);
		    if(count($name)>1) {
			    $where['tv_name'] = array('in',$tag['name']);
		    }else{
			    $where['tv_name'] = array('eq',$name[0]);
		    }	
	    }
	    if(!empty($tag['likename'])) {
		    $where['tv_name'] = array('like','%'.$tag['likename'].'%');	
	    }		
	    if(!empty($tag['wd'])) {
		    $where['tv_name|tv_content'] = array('like','%'.$tag['wd'].'%');	
	    }
        if(!empty($tag['gold'])) {
		    $gold = explode(',',$tag['gold']);
		    if(count($gold) > 1) {
			    $where['tv_gold'] = array('between',$gold[0].','.$gold[1]);
		    }else{
			    $where['tv_gold'] = array('gt',$gold[0]);
		    }
	    }
	    if(!empty($tag['golder'])) {
		    $golder = explode(',',$tag['golder']);
		    if(count($golder) > 1) {
			    $where['tv_golder'] = array('between',$golder[0].','.$golder[1]);
		    }else{
			    $where['tv_golder'] = array('gt',$golder[0]);
		    }
	    }
	    if(!empty($tag['up'])) {
		    $up = explode(',',$tag['up']);
		    if(count($up)>1) {
			    $where['tv_up'] = array('between',$up[0].','.$up[1]);
		    }else{
			    $where['tv_up'] = array('gt',$up[0]);
		    }
	    }
	    if(!empty($tag['down'])) {
		    $down = explode(',',$tag['down']);
		    if(count($down)>1) {
			    $where['tv_down'] = array('between',$down[0].','.$down[1]);
		    }else{
			    $where['tv_down'] = array('gt',$down[0]);
		    }
	    }	
        if(!empty($tag['addtime'])){
		    $time = explode(',',$tag['addtime']);
		    if(count($time) > 1) {
			    $where['tv_addtime'] = array('between',intval(strtotime($time[0])).','.intval(strtotime($time[1])));
		    }else{
			    $where['tv_addtime'] = array('gt',intval(strtotime($time[0])));
		    }			
        }			
		if($tag['prty']){
			if(check_position($tag['prty'])){
			    $where['tv_prty'] = check_position($tag['prty']);
			}
		}
        if(!empty($tag['tag'])){
		    $where['tag_name'] = array('eq',$tag['tag']);
		    $where['tag_sid'] = 7;
		    $rs = db('tag')->join('tv tv','tv.tv_id =tag_id','RIGHT');	
	    }else{
			$rs=db('tv');
		}
        if(!empty($tag['page'])){
            $url=urldecode(zanpian_list_url($GLOBALS['route'],config('params')));
		    $data = $rs->where($where)->field($tag['field'])->order($tag['order'])->paginate($tag['limit'],false,['path'=>$url]);
		}else{
			$limit_str = intval(abs($tag['start'])).",".intval(abs($tag['limit']));
			$data = $rs->where($where)->field('tv_content',true)->order($tag['order'])->limit($limit_str)->select();
		}
		if(!empty($cahce['cache_name']) && !empty($cahce['cache_time'])){
			cache::tag('foreach_tv')->set($cahce['cache_name'],$data,intval($cahce['cache_time'])); 
	    }
		return $data;
    } 

    public function week($name,$data){
	    $data=json_decode($data, true);
		if(empty($data)){
			return false;
		}	
	    $week=$this->weeklists[date("w")];
	    $weekdata=list_search($data,'week='.$week);
		
		if(empty($weekdata)){
			$weekdata=$data;
		}		
	    $time=strtotime(date("H:i"));
	    $datas=explode(chr(13),trim($weekdata[0]['data']));
		$len = count($datas);
        foreach($datas as $k=>$val){
            $datalist=explode('$',$val);
		    $ndatalist=explode('$',$datas[$k+1]);
		    if($time >= strtotime($datalist[0]) && $time < strtotime($ndatalist[0]) || $time >= strtotime($datalist[0]) && $k == $len-1){
				$array['tv_live']=$k;
			    $array['tv_datalist'][$k]['live']=1;
            }				
		    $array['tv_datalist'][$k]['time']=$datalist[0];
		    $array['tv_datalist'][$k]['name']=str_replace('#','',$datalist[1]);
		    $datalistkey[$k]=explode('#',$datalist[1]);
		    if(count($datalistkey[$k])>1){
			    $array['tv_datalist'][$k]['keywords']=$datalistkey[$k][1];	
		    }else{
			    $array['tv_datalist'][$k]['keywords']=preg_replace(array("/.*?:/","/(\(.*?)\)/","/.*?：/","/（(.*?)）/","/\d*/"),"",$datalist[1]);
		    }
	    }
        $counts = count($array['tv_datalist'])-1;
		foreach($array['tv_datalist'] as $i=>$v){
			if(($array['tv_live'] == $counts && $i>$array['tv_live']-3) || ($array['tv_live']==0 && $i < 3) || ($i >= $array['tv_live']-1 && $i <= $array['tv_live']+1)){	
		        $arrays[$i]=$v;				
		    }else{
				continue;
			}
		}
		if(!empty($arrays)){
			return $arrays;
		}else{
			return false;
		}
    }
    public function vodtv($tag){
		if(!is_array($tag)) {
            $tag=json_decode($tag, true);
        }
		$tag['limit']= !empty($tag['limit']) ? $tag['limit'] : '*';
		if(empty($tag['tv']) || empty($tag['name'])){
			return false;
		}
		if(empty(order_check($tag['order']))){
			$tag['order']='tv_addtime desc';
		}
		if($tag['tv']){
		    $tv = explode(',',$tag['tv']);
		    if(count($tv)>1) {
			    $where['tv_name'] = array('in',$tag['tv']);
		    }else{
			    $where['tv_name'] = array('eq',$tv[0]);
		    }	
		}
		if(!empty($where)){
		   $list = db('tv')->field('tv_id,tv_cid,tv_name,tv_pic,tv_letters,tv_data')->limit($limit)->where($where)->order($tag['order'])->select();
		}
		if(empty($list)){
			return false;
		}
		$date=strtotime(date('Y-m-d'));
		$time=strtotime(date("H:i"));
		foreach($list as $key=>$value){
            $array[$key]['tv_id']=$value['tv_id'];
			$array[$key]['tv_cid']=$value['tv_cid'];
			$array[$key]['tv_name']=$value['tv_name'];
			$array[$key]['tv_pic']=$value['tv_pic'];
			$array[$key]['tv_letters']=$value['tv_letters'];
		    $data=json_decode($value['tv_data'],true);
			if(!empty($data)){
			    foreach($data as $k=>$val){
					$today=strtotime(str_replace(array('年','月','日'),array('-','-',''),$val['date']));
					if($today >= $date && (strpos($val['data'],$tag['name']) !== false || !empty($tag['aliases']) && strpos($val['data'],$tag['aliases']) !== false)){
						if($val['data']){
					    $array[$key]['week_list'][$k]['week']=$val['week'];
					    $array[$key]['week_list'][$k]['date']=$today;
					    $tvs=explode(chr(13),trim($val['data']));
					    foreach($tvs as $kk=>$v){
						    $datalist=explode('$',$v);
						    $ndatalist=explode('$',$tvs[$kk+1]);
                            if(strpos($v,$tag['name']) !== false || (!empty($tag['aliases']) && strpos($v,$tag['aliases']) !== false)){
								if($time >= strtotime($datalist[0]) && $time < strtotime($ndatalist[0])){
				                    $array[$key]['week_list'][$k]['item'][$kk]['live']=1;
				                }
		                        $array[$key]['week_list'][$k]['item'][$kk]['time']=$datalist[0];
		                        $array[$key]['week_list'][$k]['item'][$kk]['name']=str_replace('#','',$datalist[1]); 
		                        continue;
                            } 						
					    }
						$array[$key]['week_list'][$k]['item']=array_values($array[$key]['week_list'][$k]['item']);
						}else{
						   continue;	
						}
					}else{
						continue;
					}
				}
				$array[$key]['week_list']=@array_values($array[$key]['week_list']);
			}
		}
		if(!empty($array)){
			
			foreach($array as $key=>$value){
			    if(empty($value['week_list'])){
					unset($array[$key]);
				}
			}
			return $array;
		}else{
			return false;
		}
    }		
	
}
// +----------------------------------------------------------------------
// | ZanPianCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.zanpiancms.com All rights reserved.
// +----------------------------------------------------------------------
// | BBS:  <http://www.zanpiancms.cc>
// +----------------------------------------------------------------------